//
//  RegisterOfPetViewController.m
//  LoveOfPet
//
//  Created by dllo on 15/11/11.
//  Copyright © 2015年 孔维. All rights reserved.
//

#import "RegisterOfPetViewController.h"
#import "KongWURLSessionHandle.h"
#import "KongWFindDoctorViewController.h"
#import "KongWFindHospitalViewController.h"
#import "KongWIllnessViewController.h"
#import "KongWDoctorCollectionViewCell.h"
#import "KongWHospitalTableViewCell.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "KongWAreaViewController.h"
#import "KongWFindDoctorDetailViewController.h"
#import "KongWFindHospitalDetailViewController.h"
#import "KongWSearchViewController.h"
#import "KongWDogWebViewController.h"
#import <SVProgressHUD.h>
#define kHeight     [UIScreen mainScreen].bounds.size.height / 667
#define kWidth      [UIScreen mainScreen].bounds.size.width / 375
@interface RegisterOfPetViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITableViewDataSource, UITableViewDelegate, AreaDelegate>
//疾病字典
@property (retain, nonatomic) NSDictionary *diseaseDic;

@property (retain, nonatomic) UIImageView *catImg;

@property (retain, nonatomic) UIScrollView *scr;

@property (retain, nonatomic) UICollectionView *collect;

@property (retain, nonatomic) UITableView *table;

@property (retain, nonatomic) NSArray *doctorArray;

@property (retain, nonatomic) NSArray *hospitalModelArray;

@property (retain, nonatomic) UILabel *areaName;

@property (copy, nonatomic) NSString *address;
@end

@implementation RegisterOfPetViewController
-(void)dealloc
{
    [_diseaseDic release];
    [_catImg release];
    [_scr release];
    [_table release];
    [_collect release];
    [_doctorArray release];
    [_hospitalModelArray release];
    [_areaName release];
    [_address release];
    
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"急诊挂号";
    self.view.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.334565033783784];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self loadData];
    [self creatSubView];
    [self creatDoctorView];
    [self creatHospitalView];
    
}

-(void)loadData
{
    [KongWURLSessionHandle handleGETWithUrlString:@"http://app.5ichong.com/app.php/tag/tags" parameters:nil showHuD:YES onView:self.view successfulBlock:^(id responseObject) {
        self.diseaseDic = responseObject;
    } failureBlock:^(NSError *error) {
        NSLog(@"Error:%@", error);
    }];
    
    if (self.address == nil) {
        [KongWURLSessionHandle handleGETWithUrlString:@"http://api.5ichong.com/app.php/doctor/find_doctor_with_index?longitude=4.9E-324&latitude=4.9E-324&city=" parameters:nil showHuD:NO onView:nil successfulBlock:^(id responseObject) {
            NSDictionary *totalDic = responseObject;
            self.doctorArray = [totalDic objectForKey:@"data"];
            if (self.doctorArray.count >= 4) {
                [self.collect reloadData];
            }
        } failureBlock:^(NSError *error) {
            NSLog(@"Error:%@", error);
        }];
        
        [KongWURLSessionHandle handleGETWithUrlString:@"http://api.5ichong.com/app.php/hospital/find_hospital_with_index?longitude=4.9E-324&latitude=4.9E-324&region=%E5%85%A8%E9%83%A8&city=" parameters:nil showHuD:NO onView:nil successfulBlock:^(id responseObject) {
            NSDictionary *totalDic = responseObject;
            self.hospitalModelArray = [totalDic objectForKey:@"data"];
            if (self.hospitalModelArray.count >= 5) {
                [self.table reloadData];
            }
        } failureBlock:^(NSError *error) {
            NSLog(@"Error:%@", error);
        }];
    }else
    {
        [KongWURLSessionHandle handleGETWithUrlString:[NSString stringWithFormat:@"http://api.5ichong.com/app.php/doctor/find_doctor_with_index?longitude=4.9E-324&latitude=4.9E-324&city=%@", self.address] parameters:nil showHuD:NO onView:nil successfulBlock:^(id responseObject) {
            NSDictionary *totalDic = responseObject;
            self.doctorArray = [totalDic objectForKey:@"data"];
            if (self.doctorArray.count >= 4) {
                [self.collect reloadData];
            }
        } failureBlock:^(NSError *error) {
            NSLog(@"Error:%@", error);
        }];
        
        NSString *region = @"%E5%85%A8%E9%83%A8";
        [KongWURLSessionHandle handleGETWithUrlString:[NSString stringWithFormat:@"http://api.5ichong.com/app.php/hospital/find_hospital_with_index?longitude=4.9E-324&latitude=4.9E-324&region=%@&city=%@", region, self.address] parameters:nil showHuD:NO onView:nil successfulBlock:^(id responseObject) {
            NSDictionary *totalDic = responseObject;
            self.hospitalModelArray = [totalDic objectForKey:@"data"];
            if (self.hospitalModelArray.count >= 5) {
                [self.table reloadData];
            }
        } failureBlock:^(NSError *error) {
            NSLog(@"Error:%@", error);
        }];
        }
    
}



-(void)creatSubView
{
    self.scr = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - kHeight * 64)];
    self.scr.contentSize = CGSizeMake(0, kHeight * 1210);
    self.scr.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scr];
    [self.scr release];
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kHeight * 62)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.scr addSubview:backView];
    [backView release];
    
    UIButton *areaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    areaBtn.frame = CGRectMake(kWidth * 10, kHeight * 10, kWidth * 60, kHeight * 40);
    [areaBtn addTarget:self action:@selector(areaBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.scr addSubview:areaBtn];
    [areaBtn release];
    
    UIImageView *areaImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"KongWiconfont-position"]];
    areaImg.frame = CGRectMake(0, kHeight * 10, kWidth * 20, kHeight * 20);
    [areaBtn addSubview:areaImg];
    [areaImg release];
    
    self.areaName = [[UILabel alloc] initWithFrame:CGRectMake(areaImg.frame.origin.x + areaImg.frame.size.width, 0, kWidth * 40, kHeight * 40)];
    self.areaName.text = @"地区";
    [areaBtn addSubview:self.areaName];
    [self.areaName release];
    
    
    UIButton *search = [UIButton buttonWithType:UIButtonTypeCustom];
    search.frame = CGRectMake(areaBtn.frame.origin.x + areaBtn.frame.size.width + kWidth * 10, areaBtn.frame.origin.y, self.view.frame.size.width - kWidth * 90, areaBtn.frame.size.height);
    [search setTitle:@"搜索:医生/医院/疾病" forState:UIControlStateNormal];
    [search setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    search.layer.cornerRadius = 5;
    search.layer.borderWidth = 1;
    [search addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:search];
    
    //创建找医生按钮
    UIButton *findDoctor = [UIButton buttonWithType:UIButtonTypeCustom];
    findDoctor.frame = CGRectMake(kWidth * 30, backView.frame.origin.y + backView.frame.size.height + kHeight * 10, self.view.frame.size.width / 10 * 2, self.view.frame.size.width / 10 * 2);
    findDoctor.layer.borderWidth = kWidth * 3;
    findDoctor.layer.borderColor = [UIColor redColor].CGColor;
    findDoctor.layer.cornerRadius = self.view.frame.size.width / 10;
    [findDoctor setTitle:@"找医生" forState:UIControlStateNormal];
    [findDoctor setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [findDoctor addTarget:self action:@selector(findDoctor) forControlEvents:UIControlEventTouchUpInside];
    [self.scr addSubview:findDoctor];
    //创建找医院按钮
    UIButton *findHospital = [UIButton buttonWithType:UIButtonTypeCustom];
    findHospital.frame = CGRectMake(self.view.frame.size.width / 10 * 2 + kWidth * 75, findDoctor.frame.origin.y, self.view.frame.size.width / 10 * 2, self.view.frame.size.width / 10 * 2);
    findHospital.layer.borderWidth = kWidth * 3;
    findHospital.layer.borderColor = [UIColor yellowColor].CGColor;
    findHospital.layer.cornerRadius = self.view.frame.size.width / 10;
    [findHospital setTitle:@"找医院" forState:UIControlStateNormal];
    [findHospital setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [findHospital addTarget:self action:@selector(findHospital) forControlEvents:UIControlEventTouchUpInside];
    [self.scr addSubview:findHospital];
    
    //创建查疾病按钮
    UIButton *examineDisease = [UIButton buttonWithType:UIButtonTypeCustom];
    examineDisease.frame = CGRectMake(findHospital.frame.origin.x + findHospital.frame.size.width + kWidth * 45, findDoctor.frame.origin.y, self.view.frame.size.width / 10 * 2, self.view.frame.size.width / 10 * 2);
    examineDisease.layer.borderWidth = kWidth * 3;
    examineDisease.layer.borderColor = [UIColor greenColor].CGColor;
    examineDisease.layer.cornerRadius = self.view.frame.size.width / 10;
    [examineDisease setTitle:@"查疾病" forState:UIControlStateNormal];
    [examineDisease setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [examineDisease addTarget:self action:@selector(examineDisease) forControlEvents:UIControlEventTouchUpInside];
    [self.scr addSubview:examineDisease];
    
    
    
    
    //创建狗狗疾病图片
    UIImageView *dogImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, findDoctor.frame.origin.y + findDoctor.frame.size.height + 10, self.view.frame.size.width / 2, kHeight * 120)];
    dogImg.image = [UIImage imageNamed:@"KongWdog.jpg"];
    
    dogImg.userInteractionEnabled = YES;
    //创建轻拍手势
    UITapGestureRecognizer *dogTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dogImage:)];
    dogTap.numberOfTapsRequired = 1;
    [dogImg addGestureRecognizer:dogTap];
    [dogTap release];
    [self.scr addSubview:dogImg];
    [dogImg release];
    
    UILabel *dogTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, dogImg.frame.size.height - kHeight * 30, dogImg.frame.size.width, kHeight * 30)];
    dogTitle.backgroundColor = [UIColor blackColor];
    dogTitle.text = @"宠物狗常见品种与疾病";
    dogTitle.textColor = [UIColor whiteColor];
    dogTitle.alpha = 0.5;
    [dogImg addSubview:dogTitle];
    [dogTitle release];
    
    
    //创建喵喵疾病图片
    self.catImg = [[UIImageView alloc] initWithFrame:CGRectMake(dogImg.frame.origin.x + dogImg.frame.size.width, dogImg.frame.origin.y, self.view.frame.size.width / 2, kHeight * 120)];
    self.catImg.image = [UIImage imageNamed:@"KongWcat.jpg"];
    
    
    self.catImg.userInteractionEnabled = YES;
    //创建轻拍手势
    UITapGestureRecognizer *catTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(catImage:)];
    catTap.numberOfTapsRequired = 1;
    [self.catImg addGestureRecognizer:catTap];
    [catTap release];
    [self.scr addSubview:self.catImg];
    [self.catImg release];
    
    UILabel *catTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, self.catImg.frame.size.height - kHeight * 30, self.catImg.frame.size.width, kHeight * 30)];
    catTitle.backgroundColor = [UIColor blackColor];
    catTitle.text = @"宠物猫病症快速查询";
    catTitle.textColor = [UIColor whiteColor];
    catTitle.alpha = 0.5;
    [self.catImg addSubview:catTitle];
    [catTitle release];
    
}

-(void)creatDoctorView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.catImg.frame.size.height + self.catImg.frame.origin.y + kHeight * 20, self.view.frame.size.width, kHeight * 240) collectionViewLayout:flow];
    self.collect.delegate = self;
    self.collect.dataSource = self;
    self.collect.backgroundColor = [UIColor whiteColor];
    [self.collect registerClass:[KongWDoctorCollectionViewCell class] forCellWithReuseIdentifier:@"doctorCollectCellIndentify"];
    [self.collect registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"doctorOfHeadCollectIndentify"];
    [self.scr addSubview:self.collect];
    [flow release];
    [self.collect release];
}

-(void)creatHospitalView
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, self.collect.frame.origin.y + self.collect.frame.size.height + 20, self.view.frame.size.width, kHeight * 600) style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.table registerClass:[KongWHospitalTableViewCell class] forCellReuseIdentifier:@"hospitalTableCellIndentify"];
    [self.scr addSubview:self.table];
    [self.table release];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 4;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(kWidth * 10, kHeight * 10, kWidth * 10, kHeight * 10);

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KongWDoctorCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"doctorCollectCellIndentify" forIndexPath:indexPath];
    [cell.img sd_setImageWithURL:[NSURL URLWithString:[[self.doctorArray objectAtIndex:indexPath.row] objectForKey:@"avatar"]]];
    cell.nameLabel.text = [[self.doctorArray objectAtIndex:indexPath.row] objectForKey:@"name"];
    cell.jobLabel.text = [[self.doctorArray objectAtIndex:indexPath.row] objectForKey:@"job"];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.view.frame.size.width - kWidth * 50) / 4, kHeight * 120);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return kWidth * 10;
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(self.view.frame.size.width, kHeight * 50);
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"doctorOfHeadCollectIndentify" forIndexPath:indexPath];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, reusable.frame.size.width, reusable.frame.size.height)];
    lable.text = @"宠物好医生";
    lable.textColor = [UIColor blueColor];
    lable.backgroundColor = [UIColor whiteColor];
    lable.font = [UIFont systemFontOfSize:kWidth * 20];
    [reusable addSubview:lable];
    [lable release];
    return reusable;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    KongWFindDoctorDetailViewController *findDoctorDetail = [[KongWFindDoctorDetailViewController alloc] init];
    NSNumber *uid = [[self.doctorArray objectAtIndex:indexPath.row] objectForKey:@"uid"];
    findDoctorDetail.udid = [uid integerValue];
    [findDoctorDetail setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:findDoctorDetail animated:YES];
    [findDoctorDetail release];
}
#pragma mark table
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHeight * 110;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KongWHospitalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hospitalTableCellIndentify"];
    [cell.img sd_setImageWithURL:[NSURL URLWithString:[[self.hospitalModelArray objectAtIndex:indexPath.row] objectForKey:@"photo_url"]]];
    cell.nameLabel.text = [[self.hospitalModelArray objectAtIndex:indexPath.row] objectForKey:@"name"];
    cell.scoreLabel.text = [NSString stringWithFormat:@"%@", [[self.hospitalModelArray objectAtIndex:indexPath.row] objectForKey:@"avg_rating"]];
    NSNumber *disNum = [[self.hospitalModelArray objectAtIndex:indexPath.row] objectForKey:@"distance"];
    CGFloat disFloat = [disNum floatValue];
    cell.distanceLabel.text = [NSString stringWithFormat:@"%.2f米", disFloat / 1000];
    cell.addressLabel.text = [[self.hospitalModelArray objectAtIndex:indexPath.row] objectForKey:@"address"];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    KongWFindHospitalDetailViewController *findHospital = [[KongWFindHospitalDetailViewController alloc] init];
    
    findHospital.udid = [[self.hospitalModelArray objectAtIndex:indexPath.row] objectForKey:@"id"];
    [findHospital setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:findHospital animated:YES];
    [findHospital release];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *head = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kHeight * 50)];
    head.text = @"周边医院";
    head.textColor = [UIColor blueColor];
    head.font = [UIFont systemFontOfSize:20];
    return head;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

-(void)search
{
    KongWSearchViewController *search = [[KongWSearchViewController alloc] init];
    search.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:search animated:YES];
    [search release];
    
}
-(void)findDoctor
{
    KongWFindDoctorViewController *findDoctor = [[KongWFindDoctorViewController alloc] init];
    findDoctor.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:findDoctor animated:YES];
    [findDoctor release];
}
-(void)findHospital
{
    KongWFindHospitalViewController *findHospital = [[KongWFindHospitalViewController alloc] init];
    findHospital.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:findHospital animated:YES];
    [findHospital release];
}
-(void)examineDisease
{
    KongWIllnessViewController *illness = [[KongWIllnessViewController alloc] init];
    illness.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:illness animated:YES];
    [illness release];
}
-(void)dogImage:(UITapGestureRecognizer *)tap
{
    KongWDogWebViewController *dogWeb = [[KongWDogWebViewController alloc] init];
    dogWeb.taget = 1;
    dogWeb.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:dogWeb animated:YES];
    [dogWeb release];
}
-(void)catImage:(UITapGestureRecognizer *)tap
{
    KongWDogWebViewController *catWeb = [[KongWDogWebViewController alloc] init];
    catWeb.taget = 2;
    catWeb.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:catWeb animated:YES];
    [catWeb release];
}

-(void)areaBtn:(id)sender
{
    KongWAreaViewController *area = [[KongWAreaViewController alloc] init];
    area.type = @"NO";
    area.delegate = self;
    [self.navigationController pushViewController:area animated:YES];
    [area release];
}

#pragma mark 代理方法
-(void)returnAreaName:(NSString *)str
{
    self.areaName.text = str;
    self.address = str;
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [SVProgressHUD dismiss];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
